//
//  FFPayOrderChooseCountryView.m
//  FFMall
//
//  Created by ale tan on 2017/9/22.
//  Copyright © 2017年 IT.Bear. All rights reserved.
//

#import "FFPayOrderChooseCountryView.h"

@interface FFPayOrderChooseCountryView ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic ,strong)NSArray *dataSources;
@property (nonatomic ,strong)ChooseCountry chooseCountryBlock;
@property (nonatomic ,strong) FBCountryModel *selectedCountry;
@property (nonatomic ,assign) NSInteger selectedIndex;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottom;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

@end

@implementation FFPayOrderChooseCountryView

+ (instancetype)chooseCountryViewWithCountries:(NSArray *)countries SelectedIndex:(NSInteger)selectedIndex{
    FFPayOrderChooseCountryView *orderView = [[[NSBundle mainBundle] loadNibNamed:@"FFPayOrderChooseCountryView" owner:nil options:nil] firstObject];
    orderView.dataSources = countries;
    orderView.selectedIndex = selectedIndex;
    orderView.selectedCountry = countries[selectedIndex];
    return orderView;
}

- (void)setChooseCountry:(ChooseCountry)chooseCountry{
    _chooseCountryBlock = chooseCountry;
}

- (void)show{
    UIView *view = [UIApplication sharedApplication].keyWindow.rootViewController.view;//[[UIApplication sharedApplication].delegate window];
    self.frame = view.bounds;
    [self layoutIfNeeded];
    [view addSubview:self];
    
    NSInteger rows = [_pickerView numberOfRowsInComponent:0];
    if (_selectedIndex<rows) {
        [_pickerView selectRow:_selectedIndex inComponent:0 animated:NO];
    }
}

- (void)awakeFromNib{
    [super awakeFromNib];
    _toBottom.constant = isDeviceIphoneX?34:0;
    _pickerView.dataSource = self;
    _pickerView.delegate = self;
}

#pragma mark -UIPickerView-
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _dataSources.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    FBCountryModel *model = _dataSources[row];
    return model.chinese_name;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    _selectedCountry = _dataSources[row];
    _selectedIndex = row;
}

#pragma mark -Events-
- (IBAction)clickBackgroundToCancle:(id)sender {
    [self removeFromSuperview];
}

//确定选择
- (IBAction)clickToConfirmChooseCountry:(id)sender {
    [self removeFromSuperview];
    if (_chooseCountryBlock) {
        _chooseCountryBlock(_selectedCountry,_selectedIndex);
    }
}

//取消选择
- (IBAction)clickToCancleChooseCountry:(id)sender {
    [self removeFromSuperview];
    if (_chooseCountryBlock) {
        _chooseCountryBlock(nil,-1);
    }
}
@end
